﻿using Ceri.Platform.EAM.Model;
using Ceri.Platform.EAM_NEW.API.Common;
using Ceri.Platform.EAM_NEW.API.Common.Helper;
using Ceri.Platform.EAM_NEW.API.Common.Model;
using Ceri.Platform.EAM_NEW.API.Services.BasicData;
using Ceri.Platform.EAM_NEW.API.Services.DTO;
using Ceri.Platform.LES.Model.login_Go;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Security.Claims;

namespace Ceri.Platform.EAM_NEW.API.Controllers
{
    /// <summary>
    /// 登录控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : BaseApiController
    {
        /// <summary>
        /// 前端登录请求方法
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="userPwd">密码</param>
        /// <returns></returns>
        [HttpGet("UserLogin")]
        public MessageModel UserLogin(string userName, string userPwd)
        {
            HttpResponseMessage httpReponseMessage = new HttpResponseMessage();
            MessageModel msg = new();
            string strApi = AppSettings.GetValue("OtherApi:CeriOSApiIpPost");
            msg = HttpHelper.GetApi<MessageModel>(strApi, "api/Login/jwttoken3.0", "name=" + userName + "&pass=" + userPwd + "");

            if (msg.success == true)
            {
                JObject resp = JsonConvert.DeserializeObject<JObject>(msg.response.ToString());
                string token = resp["token"].ToString();
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                MessageModel message2 = HttpHelper.GetApi<MessageModel>(strApi, "api/user/GetInfoByToken", "token=" + token);
                SysUserInfo data = JsonConvert.DeserializeObject<SysUserInfo>(message2.response.ToString());

                #region
                List<SysRole> AllRoles = HttpHelper.GetApi<List<SysRole>>(strApi, "api/Role/GetAllRoles", "");
                AllRoles = AllRoles.Where(s => s.Name == "设备管理系统").ToList();
                var roles = AllRoles.FirstOrDefault();
                var rolslist = AllRoles.Where(s => s.Code == roles.Code).ToList();
                MessageModel AllUserRole = HttpHelper.GetApi<MessageModel>(strApi, "api/Role/GetRoleUser", "UserID=" + data.Id);
                List<RoleUser> dataUserRole = JsonConvert.DeserializeObject<List<RoleUser>>(AllUserRole.response.ToString());
                List<int> allroleslist = new List<int>();
                List<int> dateuserrolelist = new List<int>();
                allroleslist = rolslist.Select(p => p.Id).ToList();
                dateuserrolelist = dataUserRole.Select(p => p.Id).ToList();
                var resultIntersectList = allroleslist.Intersect(dateuserrolelist).ToList();
                List<Response> list1 = new List<Response>();
                foreach (var item in resultIntersectList)
                {
                    MessageModel AllMenus = HttpHelper.GetApi<MessageModel>(strApi, "api/Permission/GetPermissionIdByRoleId", "rid=" + item);
                    var list = JsonConvert.DeserializeObject<Response>(AllMenus.response.ToString());
                    list1.Add(list);
                }
                List<int> listMerge1 = new();
                foreach (var item in list1)
                {
                    listMerge1 = listMerge1.Union(item.permissionids).ToList();
                }
                var list2 = listMerge1.Distinct().ToList();
                List<SysMenus> menulist = new List<SysMenus>();
                foreach (var item in list2)
                {
                    SysMenus AllMesu = HttpHelper.GetApi<SysMenus>(strApi, "api/PermissionDapper/GetByIdPer", "id=" + item);
                    menulist.Add(AllMesu);
                }
                menulist = menulist.Where(s => s != null).OrderBy(s => s.Sort).ToList();
                var redirect = menulist.FirstOrDefault();
                List<Tree> treelist = new List<Tree>();
                foreach (var item in menulist)
                {
                    Tree treemodel = new Tree
                    {
                        Id = item.Id,
                        path = item.LinkUrl,
                        name = item.Name,
                        component = item.LinkUrl,
                        meta = item.Icon,
                        hideChildrenInMenu = item.IsShow,
                        Pid = item.Pid
                    };
                    treelist.Add(treemodel);
                }
                foreach (var item in treelist)
                {
                    Recursion(item, treelist);
                }
                List<Tree> tree = new List<Tree>();
                var list3 = treelist.Select(s => s.children).ToList(); ;
                foreach (var item in list3)
                {
                    foreach (var index in item)
                    {
                        tree.Add(index);
                    }
                }
                foreach (var item in tree)
                {
                    treelist.Remove(item);
                }
                #endregion

                msg.status = 200;
                msg.msg = "登陆成功";
                dictionary["Id"] = data.Id;
                dictionary["Code"] = data.Code;
                dictionary["RealName"] = data.RealName;
                dictionary["Sex"] = data.Sex;
                dictionary["Token"] = token;
                dictionary["Permissionids"] = treelist.Distinct();
                msg.response = dictionary;
                httpReponseMessage.Content = new StringContent(JsonConvert.SerializeObject(msg));
            }
            else
            {
                msg.status = 400;
                msg.msg = "用户名或密码错误！";
                msg.response = "";
                httpReponseMessage.Content = new StringContent(JsonConvert.SerializeObject(msg));

            }
            return msg;
        }

        #region 递归
        /// <summary>
        /// 递归方法
        /// </summary>
        /// <param name="dto">当前要查询子节点的节点</param>
        /// <param name="list">所有的节点信息</param>
        private void Recursion(Tree dto, List<Tree> list)
        {
            var subNode = list.Where(m => m.Pid == dto.Id).ToList();
            if (subNode.Count() > 0)
            {
                dto.children = new List<Tree>();
                foreach (var item in subNode)
                {
                    dto.children.Add(item);
                    Recursion(item, list);
                }
            }
        }
        #endregion
    }
}